package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.db.dao.LitemallCategoryMapper;
import org.linlinjava.litemall.db.dao.LitemallCommodityMapper;
import org.linlinjava.litemall.db.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class LitemallCommodityService {
    @Resource
    private LitemallCommodityMapper dao;
    @Resource
    private LitemallCategoryMapper categoryDao;
    @Autowired
    private LitemallBrandInfoService brandInfoService;

    public LitemallCommodityWithBLOBs selectById(Integer id) {
        LitemallCommodityWithBLOBs commodity = brandInfoService.appendBrandInfo(dao.selectByPrimaryKey(id));
        List<String> picList = new LinkedList<>();
        String temp = commodity.getCommodityMainImage();
        if (temp == null || "".equals(temp)) {
            temp = "";
        }
        picList.add(temp);
        Collections.addAll(picList, commodity.getCommodityImage());
        commodity.setCommodityImage(picList.toArray(commodity.getCommodityImage()));
        return commodity;
    }

    public LitemallCommodity selectByIdSimple(Integer id) {
        return dao.selectByPrimaryKeySelective(id, LitemallCommodityWithBLOBs.Column.id, LitemallCommodityWithBLOBs.Column.categoryId
                , LitemallCommodityWithBLOBs.Column.brandId, LitemallCommodityWithBLOBs.Column.commodityMainImage
                , LitemallCommodityWithBLOBs.Column.commodityName, LitemallCommodityWithBLOBs.Column.commodityDescription
                , LitemallCommodityWithBLOBs.Column.commodityPromise);
    }

    public PageInfo<LitemallCommodity> selectByCondition(int page, int pageSize, Integer categoryPid, List<Integer> categoryId, List<Integer> brandId, String name, String sort) {
        List<Integer> categoryList = new LinkedList<>();
        if (categoryId != null && categoryId.size() > 0) {
            categoryList.addAll(categoryId);
        }
        if (categoryPid != null && categoryPid > 0 && categoryList.size() < 1) {
            LitemallCategoryExample example = new LitemallCategoryExample();
            example.or().andPidEqualTo(categoryPid);
            List<LitemallCategory> list = categoryDao.selectByExample(example);
            for (LitemallCategory c : list) {
                categoryList.add(c.getId());
            }
        }
        LitemallCommodityExample example = new LitemallCommodityExample();
        LitemallCommodityExample.Criteria c1 = example.or().andIsDeletedEqualTo(false);
        LitemallCommodityExample.Criteria c2 = example.or().andIsDeletedEqualTo(false);
        if (categoryList.size() > 0) {
            c1.andCategoryIdIn(categoryList);
            c2.andCategoryIdIn(categoryList);
        }
        if (brandId != null) {
            c1.andBrandIdIn(brandId);
            c2.andBrandIdIn(brandId);
        }
        if (name != null && name.length() > 0) {
            c1.andCommodityNameLike("%" + name + "%");
            c2.andCommodityDescriptionLike("%" + name + "%");
        }
        if (sort != null && sort.length() > 0) {
            example.setOrderByClause(sort);
        }
        PageHelper.startPage(page, pageSize);
        List<LitemallCommodity> commodityList = dao.selectByExample(example);
        return brandInfoService.appendBrandInfo(new PageInfo<>(commodityList));
    }

    public long countLitemallCommodity(Integer categoryPid, List<Integer> categoryId, List<Integer> brandId) {
        List<Integer> categoryList = new LinkedList<>();
        if (categoryId != null && categoryId.size() > 0) {
            categoryList.addAll(categoryId);
        }
        if (categoryPid != null && categoryPid > 0 && categoryList.size() < 1) {
            LitemallCategoryExample example = new LitemallCategoryExample();
            example.or().andPidEqualTo(categoryPid);
            List<LitemallCategory> list = categoryDao.selectByExample(example);
            for (LitemallCategory c : list) {
                categoryList.add(c.getId());
            }
        }
        LitemallCommodityExample example = new LitemallCommodityExample();
        LitemallCommodityExample.Criteria criteria = example.createCriteria().andIsDeletedEqualTo(false);
        if (categoryList.size() > 0) {
            criteria.andCategoryIdIn(categoryList);
        }
        if (brandId != null) {
            criteria.andBrandIdIn(brandId);
        }
        return dao.countByExample(example);
    }

    public int insertCommodity(LitemallCommodityWithBLOBs commodity) {
        return dao.insertSelective(commodity);
    }

    public int updateCommodity(LitemallCommodityWithBLOBs commodity) {
        return dao.updateByPrimaryKeySelective(commodity);
    }

    public int deleteCommodity(int id) {
        LitemallCommodityExample example = new LitemallCommodityExample();
        example.or().andIdEqualTo(id);
        LitemallCommodityWithBLOBs temp = new LitemallCommodityWithBLOBs();
        temp.setIsDeleted(true);
        dao.updateByExampleSelective(temp, example);
        return 1;
    }

    /**
     * 生成 商品  在OrderGoods表中..是1个order对N个goods
     * @param list
     * @return
     */
    public List<LitemallOrderGoods> generateGoods(List<LitemallOrderGoods> list) {
        for (LitemallOrderGoods commodity : list) {
            LitemallCommodity temp = selectById(commodity.getGoodsId());
            commodity.setPicUrl(temp.getCommodityMainImage());
            commodity.setGoodsName(temp.getCommodityName());
            commodity.setGoodsPriceOrigin(temp.getCommodityPrice());
        }
        return list;
    }

    public Integer categoryIdById(Integer commodityId) {
        LitemallCommodityWithBLOBs commodity = dao.selectByPrimaryKey(commodityId);
        Integer categoryId = commodity.getCategoryId();
        return categoryId;
    }




    //是否热门 ..推介 ..  默认0 false
    public PageInfo<LitemallCommodity> brandIdHotOrMarketing(Integer brandId, Integer page, Integer limit, String isHot, String marketing) {
        PageHelper.startPage(page, limit);
        LitemallCommodityExample example = new LitemallCommodityExample();
        LitemallCommodityExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(isHot)) {
            Boolean hot1 = true;
            criteria.andIsHotEqualTo(hot1).andIsDeletedEqualTo(false);
        }
        if (!StringUtils.isEmpty(marketing)) {
            Boolean marketing1 = true;
            criteria.andMarketingEqualTo(marketing1).andIsDeletedEqualTo(false);
        }
        if (brandId != null && "".equals(brandId)) {
            criteria.andBrandIdEqualTo(brandId).andIsDeletedEqualTo(false);
        }
        return new PageInfo<>(dao.selectByExample(example));
    }

    //是否降价commodity_discount   数据库decimal
    public PageInfo<LitemallCommodity> discountCommodity(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        LitemallCommodityExample example = new LitemallCommodityExample();
        LitemallCommodityExample.Criteria criteria = example.or();
        //折扣默认是0 ..大于0显示
        criteria.andCommodityDiscountGreaterThan(new BigDecimal(0)).andIsDeletedEqualTo(false);
        return new PageInfo<>(dao.selectByExample(example));
    }


    /*多条件查询*/
    public PageInfo<LitemallCommodity> findCommodityList(Map<String, String> searchMap, Integer page, Integer limit) {

        LitemallCommodityExample example = new LitemallCommodityExample();
        LitemallCommodityExample.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            //分类ID
            if (searchMap.get("categoryId") != null) {
                criteria.andCategoryIdEqualTo(Integer.parseInt(searchMap.get("categoryId")))
                        .andIsDeletedEqualTo(false);
            }
            //公司ID
            if (searchMap.get("brandId") != null) {
                criteria.andBrandIdEqualTo(Integer.parseInt(searchMap.get("brandId")))
                        .andIsDeletedEqualTo(false);
            }
            //商品的描述
            if (searchMap.get("commodityDescription") != null) {
                criteria.andCommodityDescriptionLike("%" + searchMap.get("commodityDescription") + "%")
                        .andIsDeletedEqualTo(false);
            }//商品的名字
            if (searchMap.get("commodityName") != null) {
                criteria.andCommodityNameLike("%" + searchMap.get("commodityName") + "%")
                        .andIsDeletedEqualTo(false);
            }
        }
        PageHelper.startPage(page, limit);
        return new PageInfo<>(dao.selectByExample(example));
    }

    /**
     *  三级分类 查找商品..仿 原来 ↑ selectByCondition 写..出参
     * @param page
     * @param pageSize
     * @param brandIdList
     * @param categoryIdL1
     * @param categoryIdL2
     * @param categoryIdL3
     * @param name
     * @param sort
     * @return
     */
    public PageInfo<LitemallCommodity> findByL1L2L3(Integer page, Integer pageSize,List<Integer> brandIdList,
                                                    Integer categoryIdL1, Integer categoryIdL2, Integer categoryIdL3,
                                                    String name, String sort) {
        //  List<Integer> categoryList = new LinkedList<>();//new 分类List

        LitemallCommodityExample example = new LitemallCommodityExample();
        LitemallCommodityExample.Criteria criteria = example.createCriteria();
        LitemallCommodityExample.Criteria or = example.or();
        //  如果L3不为空 ,根据分类ID查商品返回
        if (null != categoryIdL3 && !"".equals(categoryIdL3)) {
            criteria.andCategoryIdEqualTo(categoryIdL3).andIsDeletedEqualTo(false);
        } //L3 空就找L2
        else {
            //如果L2不为空 ,通过L2拿L3
            if (null != categoryIdL2 && !"".equals(categoryIdL2)) {
                List<LitemallCategory> hasL2CategoriesL3 = queryByPid(categoryIdL2);
                //拿到PID是L2的 L3
                List<Integer> categoryL3List = new ArrayList<>();
                for (LitemallCategory categoryL3 : hasL2CategoriesL3) {
                    System.out.println("CommodityService.findByL1L2L3三级分类名>>>>>>>>" + categoryL3.getName());
                    Integer categoryL3hasL2Id = categoryL3.getId();
                    categoryL3List.add(categoryL3hasL2Id);
                }

                criteria.andCategoryIdIn(categoryL3List).andIsDeletedEqualTo(false);
            }
            //如果L2 空,  拿L1  L1 不为空
         else {
              if(null != categoryIdL1 && !"".equals(categoryIdL1)){
                  //如果L1不为空 ,通过L1拿L2 ..
                  List<LitemallCategory> litemallCategoriesL2 = queryByPid(categoryIdL1);
                 //拿到PID是L1的 L2
                  List<Integer> setL3=new ArrayList<>();
                  for (LitemallCategory categoryL2 : litemallCategoriesL2) {
                      //拿到L2 ID 去求L3
                      Integer idCategoryL2 = categoryL2.getId();
                      List<LitemallCategory> litemallCategoriesL3 = queryByPid(idCategoryL2);
                      for (LitemallCategory category : litemallCategoriesL3) {
                          setL3.add(category.getId());
                      }
                  }
                  criteria.andCategoryIdIn(setL3).andIsDeletedEqualTo(false);
                     }//如果L1 为空  下一步
                }
        }
        if (name != null && name.length() > 0) {
            criteria.andCommodityNameLike("%" + name + "%");
            or.andCommodityDescriptionLike("%" + name + "%");
      }
        if (sort != null && sort.length() > 0) {
            example.setOrderByClause(sort);
        }
        if (brandIdList != null) {
            criteria.andBrandIdIn(brandIdList);
            or.andBrandIdIn(brandIdList);
        }
        PageHelper.startPage(page, pageSize);
        return brandInfoService.appendBrandInfo(new PageInfo<>(dao.selectByExample(example)));
    }

    //根据PID  求 分类 List
    private List<LitemallCategory> queryByPid(Integer pid) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andPidEqualTo(pid).andDeletedEqualTo(false);
        return categoryDao.selectByExample(example);
    }
}


